module.exports = app => {
    const express = require('express')
    const assert = require('http-assert')
    const jwt = require('jsonwebtoken')
    const AdminUser = require('../../models/AdminUser')
    const router = express.Router({
        mergeParams: true
    })

    // 定义中间件
    // 身份认证
    const authMiddleware = require('../../middleware/auth')
    // 资源获取
    const resourceMiddleware = require('../../middleware/resource')

    // 提交资源
    router.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 根据id更新资源详情
    router.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 根据id删除资源
    router.delete('/:id', async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id, req.body)
        res.send({
            success: true
        })
    })

    // 获取资源
    router.get('/', async (req, res) => {
        const queryOpts = {};
        if(req.Model.modelName === 'Category'){
            queryOpts.populate = 'parent'
        }
        const items = await req.Model.find().setOptions(queryOpts)
        res.send(items)
    })

    // 根据id获取资源详情
    router.get('/:id', async (req, res) => {
        const items = await req.Model.findById(req.params.id)
        res.send(items)
    })

    // 中间件封装通用接口，请求参数要与模型对应,比如categories --> Category,
    // 根据对应的参数操作对应的模型，降低代码冗余
    app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(),router)


    // 文件上传处理
    const multer = require('multer')
    const upload = multer({
        dest: __dirname + '/../../uploads'
    })
    app.post('/admin/api/upload', authMiddleware(), upload.single('file'), async (req, res) => {
        const file =  req.file
        file.url = `http://localhost:8848/uploads/${file.filename}`
        // 上线后地址
        // file.url = `http://123.56.228.51/uploads/${file.filename}`
        res.send(file)
    })

    //登录
    app.post('/admin/api/login', async (req, res) => {
        const { username, password } = req.body
        // 授权过程：
        // 1. 根据用户名找用户
        const user = await AdminUser.findOne({username}).select('+password')
        assert(user, 422, 'the user does not exist')

        // 2. 校验密码
        const valida = password === user.password
        assert(valida, 422, 'password mistake')

        // 3. 返回token
        const token = jwt.sign({
            id: user._id,
            username: user.username
        }, app.get('secret'))
        res.send({ token })

    })

    // middleware error handler
    app.use((err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
        next()
    })

}
